import { UploadOutlined } from '@ant-design/icons';
import {Button, Input, Upload, Form, message, Progress, Image, Select} from 'antd';
import { connect, FormattedMessage, formatMessage } from 'umi';
import React, { Component } from 'react';
import styles from './BaseView.less';
import {updateUserInfo} from "@/pages/UserSet/service";
import {hasPermission, nopermission} from "@/hasPermission";
const { Option } = Select;



function beforeUpload(file) {
  if (!hasPermission('user:update')){
    nopermission();
    return false;
  }
  let isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
  if (!isImage) {
    message.error('请选择jpg或png格式的文件!');
    return false;
  }
  let isst10M = file.size / 1024 / 1024 < 10;
  if (!isst10M) {
    message.error('文件过大！请重新上传');
  }
  const isNotEmpty = file.size > 0;
  if (!isNotEmpty) {
    message.error('文件为空！请重新上传');
  }
  return isImage && isst10M && isNotEmpty;
}

const AvatarView = ({ currentUser, avatar, handleChange, avatarLoading, percent }) => (
  <>
    <div className={styles.avatar_title}>
      <FormattedMessage id="userset.basic.avatar" defaultMessage="Avatar" />
    </div>
    <div className={styles.avatar}>
      <Image src={avatar} alt="avatar"/>
      {avatarLoading && <Progress percent={percent} style={{ opacity: 0.8 }}/>}
    </div>
    <Upload
      name='file'
      action='joker/minio/upload'
      data={{
        id: currentUser && currentUser.id,
        table: 'USERS'
      }}
      headers={{
        Authorization: 'Bearer ' + localStorage.getItem('token'),
      }}
      showUploadList={false}
      accept='image/*'
      beforeUpload={beforeUpload.bind(this)}
      onChange={handleChange.bind(this)}
    >
      <div className={styles.button_view}>
        <Button>
          <UploadOutlined />
          <FormattedMessage id="userset.basic.change-avatar" defaultMessage="Change avatar" />
        </Button>
      </div>
    </Upload>
  </>
);

class BaseView extends Component {

  constructor() {
    super();
    this.state = {
      fileList: [],
      num: 0,
      percent: 0,
      avatarLoading: false,
      avatarKey: 'updateAvatar'
    }
  }

  view = undefined;

  componentDidMount() {
    const { currentUser } = this.props;
    this.setState({
      loginName: currentUser.loginName,
      avatar: currentUser.avatar
    })
  }

  getViewDom = (ref) => {
    this.view = ref;
  };

  handleChange = info => {
    const { avatarKey, num } = this.state;
    const fileList = info.fileList;
    this.setState({ fileList });
    this.setState({ percent: info.file.percent });
    if (info.file.status == 'uploading' && num == 0){
      this.setState({
        num: 1,
        avatarLoading: true
      });
    }
    if (info.file.status === 'done') {
      let res = info.file.response;
      if(res.status == 200) {
        message.success({ content: '上传成功！', avatarKey, duration: 2 });
        this.refreshUser();
        this.setState({
          avatar: res.data
        })
      }else {
        message.error({ content: res.message, avatarKey, duration: 2 });
      }
      this.setState({
        num: 0,
        avatarLoading: false
      });
    }
  };

  refreshUser() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userSet/fetchCurrent',
    })
  };

  handleFinish = value => {
    const { loginName } = this.state;
    if (loginName == value.loginName){
      value.loginName = '';
    }
    updateUserInfo({...value}).then(res => {
      if (res.status == 200){
        this.refreshUser();
        message.success(
          formatMessage({
            id: 'userset.basic.update.success',
          })
        );
      }
    })
  };

  render() {
    const { currentUser } = this.props;
    const { avatar, avatarLoading, percent } = this.state;
    return (
      <div className={styles.baseView} ref={this.getViewDom}>
        <div className={styles.left}>
          <Form
            layout="vertical"
            onFinish={this.handleFinish}
            initialValues={currentUser}
            hideRequiredMark
          >
            <Form.Item name="id">
              <Input hidden={true}/>
            </Form.Item>
            <Form.Item
              name="loginName"
              label={formatMessage({
                id: 'userset.basic.nickname',
              })}
              rules={[
                {
                  required: true,
                  message: formatMessage(
                    {
                      id: 'userset.basic.nickname-message',
                    },
                    {},
                  ),
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="sex"
              label={formatMessage({
                id: 'userset.basic.sex',
              })}
              rules={[
                {
                  required: true,
                  message: formatMessage(
                    {
                      id: 'userset.basic.profile-sex',
                    },
                    {},
                  ),
                },
              ]}
            >
              <Select>
                <Option value="男">男</Option>
                <Option value="女">女</Option>
                <Option value="未知">未知</Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="email"
              label={formatMessage({
                id: 'userset.basic.email',
              })}
              rules={[
                {
                  required: true,
                  message: formatMessage(
                    {
                      id: 'userset.basic.email-message',
                    },
                    {},
                  ),
                },
                {
                  type: 'email',
                  message: formatMessage({
                    id: 'register.email.wrong-format',
                  }),
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="signature"
              label={formatMessage({
                id: 'userset.basic.profile',
              })}
              rules={[
                {
                  required: true,
                  message: formatMessage(
                    {
                      id: 'userset.basic.profile-message',
                    },
                    {},
                  ),
                },
              ]}
            >
              <Input.TextArea
                placeholder={formatMessage({
                  id: 'userset.basic.profile-placeholder',
                })}
                rows={4}
                maxLength={100}
              />
            </Form.Item>
            <Form.Item
              name="address"
              label={formatMessage({
                id: 'userset.basic.address',
              })}
              rules={[
                {
                  required: true,
                  message: formatMessage(
                    {
                      id: 'userset.basic.address-message',
                    },
                    {},
                  ),
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="phone"
              label={formatMessage({
                id: 'userset.basic.phone',
              })}
              rules={[
                {
                  required: true,
                  message: formatMessage(
                    {
                      id: 'userset.basic.phone-message',
                    },
                    {},
                  ),
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item>
              <Button htmlType="submit" type="primary">
                <FormattedMessage id="userset.basic.update" defaultMessage="Update Information" />
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className={styles.right}>
          <AvatarView currentUser={currentUser} avatarLoading={avatarLoading} percent={percent} avatar={avatar} handleChange={this.handleChange} />
        </div>
      </div>
    );
  }
}

export default connect(({ userSet }) => ({
  currentUser: userSet.currentUser,
}))(BaseView);
